package com.mmall.concurrence.demo;

/**
 * 素数工具类
 *
 * @author yuelinbo
 * @date 2019/3/19 10:25
 **/
public abstract class AbstractPrimeFinder {


    /**
     * 判断一个数是否为素数
     *
     * @author yuelinbo
     * @date 2019/3/19 10:28
     **/
    public boolean isPrime(final int number) {
        if (number <= 1) {
            return false;
        }
        for (int i = 2; i < number; i++) {
            if (number % i == 0){
                return false;
            }
        }
        return true;
    }


    /**
     * 统计一个区间内素数的个数
     *
     * @author yuelinbo
     * @date 2019/3/19 10:31
     **/
    public int countPrimesInRange(final int lower, final int upper) {

        int total = 0;
        for (int i = lower; i <= upper; i++) {
            if (isPrime(i)) {
                total++;
            }
        }
        return total;
    }

    public abstract int countPrimes(final int number);

    /**
     * 统计计算素数需要花费的时间
     *
     * @author yuelinbo
     * @date 2019/3/19 10:33
     **/
    public void timeAndCoumpute(final int number) {
        final long start = System.nanoTime();
        final long numberOfPrimes = countPrimes(number);
        final long end = System.nanoTime();

        System.out.printf("在 %d 下共有 %d 个素数\n", number, numberOfPrimes);
        System.out.println("TIME:"+(end - start)/1.0e9);
    }


}
